package com.mytijian.task.zookeeper;

import com.mytijian.task.util.IpAddressUtil;
import com.mytijian.task.zookeeper.path.ServerPath;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.springframework.util.StringUtils;

public class LeaderService {
    private ZookeeperRegistryCenter registryCenter;
    private Integer serverPort;

    public LeaderService(ZookeeperRegistryCenter registryCenter, Integer serverPort) {
        this.registryCenter = registryCenter;
        this.serverPort = serverPort;
    }
    public boolean isLeader() {
        String leaderData = registryCenter.get(ServerPath.instance);
        if (StringUtils.isEmpty(leaderData)) {
            return false;
        }
        return leaderData.equals(IpAddressUtil.getLocalHost()+":"+ serverPort);

    }
    public void executeInLeader() {
        // 利用leaderLatch 连接 zookeeper
        try(LeaderLatch leaderLatch = new LeaderLatch(registryCenter.getClient(), ServerPath.latch)) {
            leaderLatch.start();
            leaderLatch.await();
            if (!hasLeader()) {
                registryCenter.persistEphemeral(ServerPath.instance, ServerPath.getIntanceValue(serverPort));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public boolean isLeaderUntilBlock() {
        while (!hasLeader()) {
            executeInLeader();
        }
        return isLeader();
    }

    public boolean hasLeader() {
        return registryCenter.isExisted(ServerPath.instance);
    }
}
